﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
using Mes.仓库管理;
using Mes.原料管理;
using Mes.原料管理.Models;
using Mes.质检管理.InspectionModel;
using Newtonsoft.Json;
using System.Web.Script.Serialization;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;


namespace Mes.Materials
{
    public partial class MaterialsForm : Form
    {
        private readonly HttpClient _httpClient = new HttpClient();
        private int _currentPage = 1;
        private int _pageSize = 15; // 每页显示10条数据
        private int _totalPages = 1;
        private int _totalRecords;
        public MaterialsForm()
        {
            InitializeComponent();
            dataGridView1.CellContentClick += dataGridView1_CellContentClick;
           
            InitializeControls();
            this.TopLevel = false;//设置为非顶级窗口
            this.FormBorderStyle = FormBorderStyle.None;//隐藏边框
            this.Dock = DockStyle.Fill;//填充整个容器
        }
        /// <summary>
        /// 添加原料的信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnAdd_Click(object sender, EventArgs e)
        {
            
            try
            {
                
                // 1. 非空判断
                if (string.IsNullOrWhiteSpace(textCode.Text))
                {
                    MessageBox.Show("物料编号不能为空！");
                    return;
                }

                if (string.IsNullOrWhiteSpace(textName.Text))
                {
                    MessageBox.Show("物料名称不能为空！");
                    return;
                }
                if (string.IsNullOrWhiteSpace(textSize.Text))
                {
                    MessageBox.Show("尺寸不能为空！");
                    return;
                }
                if (string.IsNullOrWhiteSpace(textSpecification.Text))
                {
                    MessageBox.Show("规格型号不能为空！");
                    return;
                }
                if (!int.TryParse(textMaterialNum.Text, out int materialNum))
                {
                    MessageBox.Show("原料数量必须为整数！");
                    return;
                }
                if (!int.TryParse(textKucunNum.Text, out int kucunNum))
                {
                    MessageBox.Show("库存数量必须为整数！");
                    return;
                }

                if (!int.TryParse(textInventorycap.Text, out int inventorycap))
                {
                    MessageBox.Show("库存上限必须为整数！");
                    return;
                }

                if (!int.TryParse(textInventoryfloor.Text, out int inventoryfloor))
                {
                    MessageBox.Show("库存下限必须为整数！");
                    return;
                }
                var material = new
                {
                    materialNumber = textCode.Text.Trim(),
                    materialName = textName.Text.Trim(),
                    materialclassification = comType.Text.Trim(),
                    size = textSize.Text.Trim(),
                    specification = textSpecification.Text.Trim(),
                    addrNo = comAddrNo.Text.Trim(),
                    Area = textArea.Text.Trim(),
                    kucunNum = textKucunNum.Text.Trim(),
                    materialType = comMaterialType.Text.Trim(),
                    state = comState.Text.Trim(),
                    remark = textRemark.Text.Trim(),
                    materialNum = textMaterialNum.Text.Trim(),
                    inventorycap = textInventorycap.Text.Trim(),
                    inventoryfloor = textInventoryfloor.Text.Trim(),
                    materialLocation = textMaterialLocation.Text.Trim(),
                };

                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://10.223.8.19:8045/");
                    client.Timeout = TimeSpan.FromSeconds(30);
                    // 添加 Token 到请求头
                    client.DefaultRequestHeaders.Authorization =
                        new AuthenticationHeaderValue("Bearer", login.CurrentToken);

                    string json = JsonConvert.SerializeObject(material);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    HttpResponseMessage response = await client.PostAsync("api/Materials/AddMaterial", content);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseText = await response.Content.ReadAsStringAsync();
                        MessageBox.Show($"添加成功！");
                        LoadDataAsync();
                        ClearForm();
                    }
                    else
                    {
                        string errorText = await response.Content.ReadAsStringAsync();
                        MessageBox.Show($"添加失败！\n状态码: {(int)response.StatusCode}\n错误信息: {errorText}");
                    }
                }
            }
            catch (HttpRequestException ex)
            {
                MessageBox.Show($"网络请求失败: {ex.Message}");
            }
            catch (JsonException ex)
            {
                MessageBox.Show($"JSON序列化失败: {ex.Message}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生未知错误: {ex.Message}");
            }
        }

        // 清空表单方法
        private void ClearForm()
        {
            textCode.Text = "";
            textName.Text = "";
            comType.DataSource = null;
            comType.Text = "";
            textSize.Text = "";
            textSpecification.Text = "";
            comAddrNo.DataSource = null;
            comAddrNo.Text = "";
            textArea.Text = "";
            textKucunNum.Text = "";
            comMaterialType.DataSource = null;
            comMaterialType.Text = "";
            comState.DataSource = null;
            comState.Text = "";
            textRemark.Text = "";
            textMaterialNum.Text = "";
            textInventorycap.Text = ""; 
            textInventoryfloor.Text = "";
            textMaterialLocation.Text = "";
            comType.SelectedIndex = -1;
            // 清空其他控件...
        }
        /// <summary>
        /// 分页显示
        /// </summary>
        private void InitializeControls()
        {
            // 设置DataGridView样式
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.ReadOnly = true;
            // 检查是否已存在序号列，避免重复添加
            if (dataGridView1.Columns["colIndex"] ==null)
            {
                DataGridViewTextBoxColumn indexColumn = new DataGridViewTextBoxColumn
                {
                    Name = "colIndex",
                    HeaderText = "序号",
                    ReadOnly = true
                };
                dataGridView1.Columns.Insert(0, indexColumn); // 插入到第一列
            }
            // 添加列（示例，根据实际需求调整）
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name="id",
                DataPropertyName = "id",
                HeaderText = "ID",
                Visible=false,
            });

            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "materialNumber",
                HeaderText = "原料编号"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "materialName",
                HeaderText = "原料名称"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "materialclassification",
                HeaderText = "原料分类"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "size",
                HeaderText = "尺寸"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "specification",
                HeaderText = "规格"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "addrNo",
                HeaderText = "原料属性"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "area",
                HeaderText = "单位"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "kucunNum",
                HeaderText = "库存数量"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "materialType",
                HeaderText = "原料类型"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "state",
                HeaderText = "状态"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "remark",
                HeaderText = "备注"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "materialNum",
                HeaderText = "原料数量"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "inventorycap",
                HeaderText = "库存上限"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "inventoryfloor",
                HeaderText = "库存下限"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "materialLocation",
                HeaderText = "原料位置"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "createName",
                HeaderText = "创建人"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "updateName",
                HeaderText = "修改人"
            });
            //初始化分页信息显示控件
            lblPageInfo.Text = $"当前页: {_currentPage} / 总页数: 0, 总记录数: 0";
            // 初始加载数据
            LoadDataAsync();
        }
        // 更新分页信息显示
        private void UpdatePaginationDisplay()
        {
            lblPageInfo.Text = $"当前页: {_currentPage} / 总页数: {_totalPages}, 总记录数: {_totalRecords}";
        }
        private void btnCha_Click(object sender, EventArgs e)
        {
            _currentPage = 1; // 查询时重置到第一页
             LoadDataAsync();
        }
        // 首页按钮点击事件
        private void btnFirst_Click(object sender, EventArgs e)
        {
            _currentPage = 1;
            LoadDataAsync();
        }
        private void btnPrev_Click(object sender, EventArgs e)
        {
            if (_currentPage > 1)
            {
                _currentPage--;
                LoadDataAsync();
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (_currentPage < _totalPages)
            {
                _currentPage++;
                LoadDataAsync();
            }
        }
        // 尾页按钮点击事件
        private void btnLast_Click(object sender, EventArgs e)
        {
            _currentPage = _totalPages;
            LoadDataAsync();
        }
        private void UpdateRowIndices()
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                if (!dataGridView1.Rows[i].IsNewRow)
                {
                    dataGridView1.Rows[i].Cells["colIndex"].Value = (i + 1).ToString();
                }
            }
        }
        private async Task LoadDataAsync()
        {
            try
            {
                // 构建查询参数
                var queryParams = new StringBuilder();
                queryParams.Append($"Index={_currentPage}");
                queryParams.Append($"&Size={_pageSize}");

                if (!string.IsNullOrWhiteSpace(textMaterCode.Text))
                    queryParams.Append($"&MaterialNumber={textMaterCode.Text.Trim()}");

                if (!string.IsNullOrWhiteSpace(textMaterName.Text))
                    queryParams.Append($"&MaterialName={textMaterName.Text.Trim()}");

                // 调用API
                _httpClient.DefaultRequestHeaders.Authorization =
                       new AuthenticationHeaderValue("Bearer", login.CurrentToken);
                string url = $"http://10.223.8.19:8045/api/Materials/GetMaterial?{queryParams}";
                string jsonResponse = await _httpClient.GetStringAsync(url);

                // 解析响应
                var serializer = new JavaScriptSerializer();
                var apiResponse = serializer.Deserialize<MaterialsApiResponse>(jsonResponse);

                if (apiResponse?.code == 200 && apiResponse.data?.datas !=null)
                {
                    // 更新分页信息
                    _totalRecords = apiResponse.data.totalCount;
                    _totalPages = (int)Math.Ceiling((double)_totalRecords / _pageSize);
                    // 绑定数据到 DataGridView
                    dataGridView1.DataSource = apiResponse.data.datas;

                    // 更新分页按钮状态
                    UpdatePaginationButtons();
                    UpdatePaginationDisplay();
                    UpdateRowIndices();
                }
                else
                {
                    MessageBox.Show($"数据加载失败: {apiResponse?.msg ?? "未知错误"}");
                }
                if (!dataGridView1.Columns.Contains("btnEdit"))
                {
                    DataGridViewButtonColumn editColumn = new DataGridViewButtonColumn();
                    editColumn.Name = "btnEdit";
                    editColumn.HeaderText = "编辑";
                    editColumn.Text = "编辑";
                    editColumn.UseColumnTextForButtonValue = true;
                    dataGridView1.Columns.Add(editColumn);
                }

                // 添加“删除”按钮列
                if (!dataGridView1.Columns.Contains("btnDelete"))
                {
                    DataGridViewButtonColumn deleteColumn = new DataGridViewButtonColumn();
                    deleteColumn.Name = "btnDelete";
                    deleteColumn.HeaderText = "删除";
                    deleteColumn.Text = "删除";
                    deleteColumn.UseColumnTextForButtonValue = true;
                    dataGridView1.Columns.Add(deleteColumn);
                }
            }
            catch (HttpRequestException ex)
            {
                MessageBox.Show($"网络错误: {ex.Message}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误: {ex.Message}");
            }
        }


        private void UpdatePaginationButtons()
        {
           
            btnPrev.Enabled = (_currentPage > 1);
            btnNext.Enabled = (_currentPage < _totalPages);
            // 更新分页按钮状态（在加载数据后调用）
           
            btnFirst.Enabled = (_currentPage > 1);
            btnLast.Enabled = (_currentPage < _totalPages);
   

        }

        /// <summary>
        /// 刷新按鈕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnShua_Click(object sender, EventArgs e)
        {
            textMaterCode.Text = "";
            textMaterName.Text = "";
            LoadDataAsync();
        }

        /// <summary>
        /// 调用删除的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // 确保点击的是“删除”按钮列
            if (e.RowIndex >= 0 && e.ColumnIndex == dataGridView1.Columns["btnDelete"].Index)
            {
                // 获取当前行的 MaterialId
                string materialId = dataGridView1.Rows[e.RowIndex].Cells["id"].Value.ToString();

                // 调用删除方法
                await DeleteMaterial(materialId);
            }
            else if (e.RowIndex >= 0 && e.ColumnIndex == dataGridView1.Columns["btnEdit"].Index)
            {
                // 这里可以直接调用 btnEdit_Click 逻辑，或者提取公共代码
                string materialId = dataGridView1.Rows[e.RowIndex].Cells["id"].Value.ToString();
                EditForm editForm = new EditForm(materialId);
                if (editForm.ShowDialog() == DialogResult.OK)
                {
                    await LoadDataAsync();
                }
            }
        }

        private async Task DeleteMaterial(string materialId)
        {
            try
            {
                // 1. 确认删除
                if (MessageBox.Show(
                    "确定要删除该原料吗？",
                    "警告",
                    MessageBoxButtons.YesNo) != DialogResult.Yes)
                {
                    return;
                }

                // 2. 调用删除接口（参数放在请求体中，而不是URL）
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://10.223.8.19:8045/");

                    // 构造请求体（如果后端要求）
                    var requestData = new
                    {
                        Id = materialId
                    };
                    client.DefaultRequestHeaders.Authorization =
                       new AuthenticationHeaderValue("Bearer", login.CurrentToken);
                    string json = JsonConvert.SerializeObject(requestData);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    // 发送 PUT 请求
                    HttpResponseMessage response = await client.PostAsync(
                        "api/Materials/DelMaterial",
                        content);

                    // 3. 处理响应
                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("删除成功！");
                        LoadDataAsync(); // 刷新数据
                    }
                    else
                    {
                        string error = await response.Content.ReadAsStringAsync();
                        MessageBox.Show($"删除失败：{response.StatusCode}\n{error}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除失败：{ex.Message}");
            }
        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btndaochu_Click(object sender, EventArgs e)
        {
            try
            {
                // 1. 调用后端接口获取数据（Excel 文件流）
                byte[] excelData = await DownloadExcelFromServerAsync();

                // 2. 保存到本地文件
                string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "原料信息.xlsx");
                File.WriteAllBytes(filePath, excelData);

                // 3. 提示用户导出成功
                MessageBox.Show($"文件已成功导出到桌面：{filePath}", "导出成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        // 调用后端接口下载 Excel 文件
        private async Task<byte[]> DownloadExcelFromServerAsync()
        {
            using (HttpClient client = new HttpClient())
            {
                
                string apiUrl = "http://10.223.8.19:8045/api/Materials/Daochu";
                client.DefaultRequestHeaders.Authorization =
                       new AuthenticationHeaderValue("Bearer", login.CurrentToken);
                // 发送 GET 请求（或 POST 请求，根据后端要求）
                HttpResponseMessage response = await client.GetAsync(apiUrl);

                // 检查响应状态
                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception($"HTTP 请求失败，状态码：{response.StatusCode}");
                }

                // 读取返回的 Excel 文件流
                return await response.Content.ReadAsByteArrayAsync();
            }
        }

        private void textCode_Paint(object sender, PaintEventArgs e)
        {

        }

     
    }
}
